package com.wise.wing.activity.main;

import com.wise.wing.R;
import com.wise.wing.views.CommonNavigationBar;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


/**
 * 自定的用于显示网页的Activity, Intent中需要传入title与url
 * 
 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
 * 
 * @author ZhuFan
 * @Date: 2015-6-12
 */
public class WebActivity extends BaseActivity implements OnClickListener {

	private CommonNavigationBar navi;
	private WebView web;
	private ProgressBar progress;
	private boolean isOverrideTitle = true;
	private String html;

	private WebViewClient mClient = new WebViewClient() {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		public void onReceivedSslError(WebView view,
				android.webkit.SslErrorHandler handler,
				android.net.http.SslError error) {
			handler.proceed();
		};
	};

	private WebChromeClient mChromeClient = new WebChromeClient() {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			setNewProgress(newProgress);
			super.onProgressChanged(view, newProgress);

		}

		@Override
		public void onReceivedTitle(WebView view, String title) {
			if (isOverrideTitle)
				navi.setTitle(title);
			super.onReceivedTitle(view, title);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_web);

		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		navi = (CommonNavigationBar) findViewById(R.id.navi);
		web = (WebView) findViewById(R.id.web);
		progress = (ProgressBar) findViewById(R.id.progress);
	}

	@Override
	public void init() {
		navi.setListener(null);
		navi.setTitle(getIntent().getStringExtra("title"));
		html = getIntent().getStringExtra("html");
		web.setWebViewClient(mClient);
		web.setWebChromeClient(mChromeClient);
		
		if(html == null || html.length() <= 0) {
			web.loadUrl(getIntent().getStringExtra("url"));
		} else {
			web.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
		}
		
		isOverrideTitle = getIntent().getBooleanExtra("isOverrideTitle", true);
	}

	@Override
	public void addListeners() {
	}

	private void setNewProgress(int newProgress) {
		progress.setVisibility(View.VISIBLE);
		progress.setProgress(newProgress);
		if (newProgress >= 100)
			progress.setVisibility(View.GONE);
	}

	@Override
	public void onBackPressed() {
		// web.goBack();
		super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		web.goBack();
	}
}
